package kt.com.bilin.coin.ui.fragment

import android.os.Bundle
import android.view.View
import com.bilin.coin.ApiConstant
import com.bilin.coin.R
import com.bilin.coin.bean.CommonSuccessEvent
import com.bilin.coin.network.RetrofitConfig
import com.bilin.coin.tools.AlertUtils
import com.bilin.coin.utils.SharedPreferencesUtils
import kotlinx.android.synthetic.main.fragment_v2_my.*
import kt.com.bilin.coin.api.API_SERVICE
import kt.com.bilin.coin.api.ApiObserver
import kt.com.bilin.coin.api.toData
import kt.com.bilin.coin.bean.MoneyBean
import kt.com.bilin.coin.bean.UserInfoBean
import kt.com.bilin.coin.common.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MyFragment : BaseFragment(R.layout.fragment_v2_my) {
    private var mIsLogin = false
    private var mKycStatus = "0"
    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        bindViewClick(this,
                rlCoupon, tvLogin, tvRegister, rlAboutUs, rlFeedback, ivStar,
                rlGuide, ivSafe, llPoints, llJixiao, llSeed, llGoldBean,
                llMyTeam, tvExit, tvInviteNow, llRealAuth, llMyMill, llMyWallet)
        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setOnRefreshListener { onReload() }
        onReload()
    }

    override fun initData(rootView: View?, savedInstanceState: Bundle?) {
        tvVersion.text = "当前版本V：${getString(R.string.version_name)}"
    }

    private fun onReload() {
        launchUI({
            handUserInfo(API_SERVICE.getSession().toData())
            handWallet(API_SERVICE.getMoney().toData())
        }, ApiObserver(context, refreshLayout = refreshLayout))
    }

    private fun handUserInfo(userInfoBean: UserInfoBean?) {
        userInfoBean?.run {
            mIsLogin = isLogin
            mKycStatus = kycStatus
            if (isLogin) {
                groupUserInfo.visibility = View.VISIBLE
                groupNotLogin.visibility = View.GONE
                tvPhone.text = mobile
                tvExit.visibility = View.VISIBLE
            } else {
                groupUserInfo.visibility = View.GONE
                groupNotLogin.visibility = View.VISIBLE
                tvExit.visibility = View.GONE
            }
            tvInviteCode.text = "邀请码:$inviteCode"
        }
    }

    private fun handWallet(moneyBean: MoneyBean?) {
        moneyBean?.run {
            tvGold.text = jd.formatDouble()
            tvSeed.text = zz.formatDouble()
            tvPoint.text = gf.formatDouble()
            tvJx.text = jx.formatDouble()
            tvBlNum.text = "拥有${blq.formatDouble()}张比邻券"
            tvLevel.text = "Lv $level"
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            tvLogin -> ARouterNavigation("/auction/LoginActivity")
            tvRegister -> ARouterNavigation("/auction/RegisterActivity")
        }
        if (!mIsLogin) {
            ARouterNavigation("/auction/LoginActivity")
            return
        }
        when (v) {
            tvExit -> AlertUtils.dialog(requireActivity(), "提示", "您确定退出登录？") {
                launchUI({ API_SERVICE.logout().toData() }, ApiObserver(context) {
                    EventBus.getDefault().post(CommonSuccessEvent(CommonSuccessEvent.LogoutSuccess))
                    logoutSuccess()
                })
            }
            rlGuide -> ARouterNavigation("/common/WebPageLoading") {
                withString("url", RetrofitConfig.newsUrl + 24)
                withString("title", "新手指南")
            }
            rlAboutUs -> ARouterNavigation(PATH_ABOUT_US)
            rlFeedback -> ARouterNavigation("/v2/user/feedback")
            llMyWallet -> AlertUtils.dialog(requireActivity()) { }
            llMyMill -> ARouterNavigation(PATH_Mill)
            tvInviteNow -> ARouterNavigation("/auction/InviteActivity")
            rlCoupon -> ARouterNavigation("/auction/CouponActivity")
            ivSafe -> ARouterNavigation("/safe/SafeActivity")
            llPoints -> ARouterNavigation("/auction/PointDetailActivity")
            llJixiao -> ARouterNavigation("/auction/JiXiaoDetailActivity")
            llSeed -> ARouterNavigation("/auction/SeedDetailActivity")
            llGoldBean -> ARouterNavigation("/auction/GoldBeanDetailActivity")
            llMyTeam -> ARouterNavigation("/auction/MyTeamActivity")
            llRealAuth -> toReal()
            ivStar -> openUrl(URL_STAR, "星级达人")
        }
    }

    private fun toReal() {
        //身份认证状态 0未认证 1审核中 2已认证 3认证失败
        when (mKycStatus) {
            "0" -> ARouterNavigation("/v2/safe/AuthActivity")
            "1" -> "审核中".toastMessageLong()
            "2" -> "已认证".toastMessageLong()
            "3" -> ARouterNavigation("/safe/AuthFailureActivity")
        }
    }

    private fun logoutSuccess() {
        mIsLogin = false
        groupNotLogin.visibility = View.VISIBLE
        groupUserInfo.visibility = View.GONE
        tvExit.visibility = View.GONE
        tvGold.text = "0"
        tvSeed.text = "0"
        tvPoint.text = "0"
        tvJx.text = "0"
        tvInviteCode.text = "邀请码:"
        tvBlNum.text = "拥有0张比邻券"
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.CSRF_TOKEN, "")
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.LoginSmsToken, "")
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.Mobile, "")
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsHasSafeWord, "")
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.IsLogin, "")
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USER_ID, "")
        SharedPreferencesUtils.getInstance().saveData(ApiConstant.USERINFO_JSON, "")
        UserDataCache.clear()
    }

    /**
     * 登录成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun loginSuccessEvent(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.LoginSuccess) {
            onReload()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    /**
     * 退出成功
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun logoutSuccessEvent(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.LogoutSuccess) {
            logoutSuccess()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    /**
     * 认证成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun authSuccessEvent(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.AuthSuccess) {
            onReload()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    /**
     * 头像更新成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun avatarSuccessEvent(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.UpdateAvatarSuccess) {
            //showAvatar()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    /**
     * 昵称更新成功
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun nickSuccessEvent(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.UpdateNickSuccess) {
            onReload()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    /**
     * 去实名
     *
     * @param commonSuccessEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun goToReal(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.GOTOREAL) {
            toReal()
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }

    /**
     * 去邀请
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun goToInvite(commonSuccessEvent: CommonSuccessEvent) {
        if (commonSuccessEvent.type == CommonSuccessEvent.GOTOINVITE) {
            ARouterNavigation("/auction/InviteActivity")
        }
        EventBus.getDefault().removeStickyEvent(commonSuccessEvent)
    }
}